//
//  TRUserLoginViewController.m
//  WeiMiLan
//
//  Created by anan on 14/12/28.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRUserLoginViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "QLPropertyUtils.h"
@interface TRUserLoginViewController ()

@end

@implementation TRUserLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //[self initNavigation];
    
//    NSAttributedString *str = [[NSAttributedString alloc] initWithString:self.textFieldAccount.placeholder attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
//    self.textFieldAccount.attributedPlaceholder = str;
//    str = [[NSAttributedString alloc] initWithString:self.textFieldPassword.placeholder attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
//    self.textFieldPassword.attributedPlaceholder = str;
    
    if ([QLPublic isWXAppInstalled]){
        self.buttonWeixin.hidden = NO;
    }else{
        self.buttonWeixin.hidden = YES;
    }
    if ([TencentOAuth iphoneQQInstalled]) {
        self.buttonQQ.hidden = NO;
    }else{
        self.buttonQQ.hidden = YES;
    }
    
    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr{
    [self.textFieldAccount resignFirstResponder];
    [self.textFieldPassword resignFirstResponder];
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"";
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(exit) forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.rightButton.hidden = YES;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(WXLogin:)
                                                 name: @"WXLogin"
                                               object: nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFieldChanged:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:self.textFieldAccount];
    
    NSString *account = [QLPropertyUtils getStringByKey:@"account" defaultValue:@""];
    if (account) {
        self.textFieldAccount.text = account;
        NSString *urlHeader = [QLPropertyUtils getStringByKey:[NSString stringWithFormat:@"userHeader_%@",account] defaultValue:nil];
        if (urlHeader) {
            self.imageViewUserHeader.layer.masksToBounds = YES;
            self.imageViewUserHeader.layer.cornerRadius = 40; //设置图片圆角的尺度
            [self.imageViewUserHeader sd_setImageWithURL:[NSURL URLWithString:urlHeader] placeholderImage:[UIImage imageNamed:@"userlogin_usericon"]];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"WXLogin" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)WXLogin:(NSNotification *)note
{
    NSDictionary *dic = note.userInfo;
    [self thirdLogin:[dic ql_stringForKey:@"s"] andUser:[dic ql_stringForKey:@"loginName"] nickname:[dic ql_stringForKey:@"nickname"] headerUrl:[dic ql_stringForKey:@"headerUrl"] type:0];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    BOOL b = [QLPropertyUtils getBoolByKey:@"guide" defaultValue:YES];
//    if (b) {
//        TRGuideViewController *vc = [[TRGuideViewController alloc] init];
//        [self presentViewController:vc animated:YES completion:^{
//            [QLPropertyUtils putBoolByKey:@"guide" value:NO];
//        }];
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)loginAction:(UIButton *)sender
{
    if (self.textFieldAccount.text.length==0) {
        [SVProgressHUD showErrorWithStatus:@"请输入用户名"];
        return;
    }
    if (self.textFieldPassword.text.length==0) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    [QLMaskUtil showMaskLoadingWithView:self.view];
    [ApplicationDelegate.webAPI logInWithUserName:self.textFieldAccount.text andPassword:self.textFieldPassword.text completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        if (state==1&&responseObject) {
            NSString *msg=[NSString stringWithFormat:@"%@",responseObject[@"MESSAGE_INFO"][@"CODE"]];
            if ([msg isEqualToString:@"0000"]) {
                //去用户id
                NSString *idString=responseObject[@"LOGIN_USER_RSP"][@"UPLOAD_URL"];
                NSArray *idArr=[idString componentsSeparatedByString:@"?userId="];
                ApplicationDelegate.currentUserId=[idArr lastObject];
                ApplicationDelegate.uploadUrl = [NSURL URLWithString:idString];
                [NSStandardUserDefaults setObject:self.textFieldAccount.text forKey:@"USER_NAME"];
                [NSStandardUserDefaults setObject:self.textFieldPassword.text forKey:@"USER_PASSWORD"];
                [NSStandardUserDefaults setObject:[idArr lastObject] forKey:@"USER_ID"];
                [NSStandardUserDefaults setObject:idString forKey:@"USER_URL"];
                [NSStandardUserDefaults synchronize];
                [ToolKit saveUser:self.textFieldAccount.text userid:[idArr lastObject]];
                NSString *uid = [NSString stringWithFormat:@"%@",[idArr lastObject]];
                [[QLUserManager shareInstance] saveUserInfo:responseObject[@"LOGIN_USER_RSP"]];
                [[QLUserManager shareInstance] detailWithUserId:(int)[uid integerValue] callback:^(BOOL isCache, id data) {
                    [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
                    [self exit];
                }];
            }else
            {
                if ([msg isEqualToString:@"9998"]) {
                    [SVProgressHUD showSuccessWithStatus:@"用户名或密码错误"];
                    self.textFieldPassword.text=@"";
                }
            }
        }
    }];
}

- (IBAction)buttonResigerAciton:(id)sender
{
    TRUserRegisterViewController *vc = [[TRUserRegisterViewController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)exit
{
    BOOL b = [[QLUserManager shareInstance] isLoginUser];
    if (b==NO) {
        return;
    }
    if (ApplicationDelegate.ddVC.rootViewController==self) {
        ApplicationDelegate.ddVC.rootViewController=ApplicationDelegate.rootVC;
        return;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)thirdLogin:(NSString *)s andUser:(NSString *)loginName nickname:(NSString*)nickname headerUrl:(NSString*)headerUrl type:(int)type
{
    [QLMaskUtil showMaskLoadingWithView:self.view];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic ql_setObject:loginName forKey:@"loginName"];
    [dic ql_setObject:nickname forKey:@"nickname"];
    [dic ql_setInterge:type forKey:@"channel"];
    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager POST:s parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        //系统自带JSON解析
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"requestTmp%@----resData%@---------resultDic%@",requestTmp,resData,resultDic);
        [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
        NSArray *arr = [[ToolKit getUser] componentsSeparatedByString:@"|"];
        ApplicationDelegate.currentUserId=[NSString stringWithFormat:@"%@",resultDic[@"userId"]];
        [NSStandardUserDefaults setObject:[NSString stringWithFormat:@"%@",resultDic[@"userId"]] forKey:@"USER_ID"];
        
        NSString *idString=[NSString stringWithFormat:@"http://ping.vsmu.cn/app/client-upload-pic?userId=%@",resultDic[@"userId"]];
        
        ApplicationDelegate.uploadUrl = [NSURL URLWithString:idString];
        [NSStandardUserDefaults setObject:idString forKey:@"USER_URL"];
        
        ApplicationDelegate.userName=arr[0];
        [NSStandardUserDefaults setObject:@"" forKey:@"USER_PASSWORD"];
        [NSStandardUserDefaults setObject:arr[0] forKey:@"USER_NAME"];
        [NSStandardUserDefaults synchronize];
        
        [ApplicationDelegate.leftVC updateUserInfo];
                
        [QLPropertyUtils putStringByKey:@"UPLOAD_URL" value:idString];
        
        [[NSUserDefaults standardUserDefaults] setObject:headerUrl forKey:@"urlHeader"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:resultDic];
        [userInfo ql_setObject:[resultDic ql_stringForKey:@"userId"] forKey:@"ID"];
        [userInfo ql_setObject:arr[0] forKey:@"NAME"];
        [[QLUserManager shareInstance] saveUserInfo:userInfo];
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];

        [dic ql_setObject:nickname forKey:@"name"];

        [dic ql_setInterge:[userInfo ql_intForKey:@"ID"] forKey:@"userId"];
        [QLMaskUtil showMaskLoadingWithView:self.view];
        AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
        requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        [requestManager POST:@"http://ping.vsmu.cn/app/Interface/User?type=9004" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dic = responseObject;
            if ([[dic[@"MESSAGE_INFO"] ql_stringForKey:@"CODE"] isEqualToString:@"0000"]) {
                [[QLUserManager shareInstance] detailWithUserId:[userInfo ql_intForKey:@"ID"] callback:^(BOOL isCache, id data) {

                    [QLMaskUtil hideLoadingMaskWithView:self.view];
                    [self exit];
                }];
            }else{
                [QLMaskUtil hideLoadingMaskWithView:self.view];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [QLMaskUtil hideLoadingMaskWithView:self.view];
        }];

        
        
        
        [[QLUserManager shareInstance] detailWithUserId:[resultDic ql_intForKey:@"userId"] callback:^(BOOL isCache, id data) {
            [QLMaskUtil hideLoadingMaskWithView:self.view];
            
            if (data) {
                NSDictionary *dic = data;
                NSString *phoneNum = [dic ql_stringForKey:@"PHONE"];
                NSString *name = [dic ql_stringForKey:@"NAME"];
                if (name||name.length>20) {
                    [[QLUserManager shareInstance] updateWithUserId:[dic ql_intForKey:@"ID"] phone:phoneNum name:nickname headerUrl:headerUrl callback:^(BOOL isCache, id data) {
                        [self exit];
                    }];
                }else{
                    [self exit];
                }
            }else{
                [self exit];
              //  MMProgressHUDShowError(@"提交失败，请重试");
            }
        }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        [self exit];
      //  MMProgressHUDShowError(@"提交失败，请重试");
    }];
    
}

/**
 *
 *
 *  @param loginName
 *  @param nickname
 *  @param headerUrl
 *  @param type      type =0 是微信  =1 是微博  =3 是QQ
 */
- (void)thirdLogin:(NSString *)loginName nickname:(NSString*)nickname headerUrl:(NSString*)headerUrl type:(int)type
{
    NSString *getPrepayIdUrl = @"http://ping.vsmu.cn/app/third-party-login";
    [self thirdLogin:getPrepayIdUrl andUser:loginName nickname:nickname headerUrl:headerUrl type:type];
    NSLog(@"tpye======%d",type);




}

- (IBAction)loginsAction:(UIButton *)sender
{
    switch (sender.tag) {
        case 0:
        {
            SendAuthReq* req =[[SendAuthReq alloc] init];
            req.scope = @"snsapi_userinfo";
            req.state = @"123";
            [WXApi sendReq:req];
            
            
            UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
            
            snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
                
                if (response.responseCode == UMSResponseCodeSuccess) {
                    
                    UMSocialAccountEntity *wechatSnsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:UMShareToWechatSession];
                    
                    NSLog(@"username is %@, uid is %@, token is %@ url is %@",wechatSnsAccount.userName,wechatSnsAccount.usid,wechatSnsAccount.accessToken,wechatSnsAccount.iconURL);
                    NSLog(@"--------------------");
                    NSLog(@"%@",wechatSnsAccount);
//                    NSString *filePath;
//                    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//                    filePath = [path stringByAppendingPathComponent:@"userInfo"];
//                    filePath = [filePath stringByAppendingString:@".plist"];
//                    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:filePath];
//                    if (dictionary.count<=1) {
//                        [dictionary setValue:wechatSnsAccount.usid forKey:@"useId"];
//                        [dictionary setValue:wechatSnsAccount.userName forKey:@"userName"];
//                        [dictionary setValue:wechatSnsAccount.iconURL forKey:@"iconURL"];
//                        
//                        [dictionary writeToFile:filePath atomically:YES];
//                        NSFileManager *fileManager = [NSFileManager defaultManager];
//                        [fileManager removeItemAtPath:path error:nil];
//                
//                    }
                //    NSDictionary *snsAccountDic = [UMSocialAccountManager socialAccountDictionary];
               
                    [ToolKit saveUser:wechatSnsAccount.userName userid:wechatSnsAccount.usid];
                    [self thirdLogin:wechatSnsAccount.usid nickname:wechatSnsAccount.userName headerUrl:wechatSnsAccount.iconURL type:2];
                    
                    
                }
                
            });
            
        }
            break;
        case 1:
        {
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
                [UMSocialControllerService defaultControllerService].socialUIDelegate = self;
                UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
                snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
                    
                    if (response.responseCode == UMSResponseCodeSuccess) {
                        NSLog(@"成功！");
                        
                        NSDictionary *snsAccountDic = [UMSocialAccountManager socialAccountDictionary];
                        UMSocialAccountEntity *qqAccount = [snsAccountDic valueForKey:UMShareToQQ];
                        [ToolKit saveUser:qqAccount.userName userid:qqAccount.usid];
                        [self thirdLogin:qqAccount.usid nickname:qqAccount.userName headerUrl:qqAccount.iconURL type:0];
                    }
                });
            }
        }
            break;
        case 2:
        {
            [UMSocialControllerService defaultControllerService].socialUIDelegate = self;
            UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
            snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
                
                if (response.responseCode == UMSResponseCodeSuccess) {
                    UIImage *image = [UIImage imageNamed:@"100.jpg"];
                    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToSina] content:@"#微米兰#奢侈品微商助手！奢侈品货源哪里找！奢侈品微店哪里开!应用商店找微米兰！ 官网：http://www.vsmu.cn/  @微米兰" image:image location:nil urlResource:nil presentedController:nil completion:^(UMSocialResponseEntity *response){
                        if (response.responseCode == UMSResponseCodeSuccess) {
                            NSLog(@"分享成功！");
                            
                            NSDictionary *snsAccountDic = [UMSocialAccountManager socialAccountDictionary];
                            UMSocialAccountEntity *sinaAccount = [snsAccountDic valueForKey:UMShareToSina];
                            [ToolKit saveUser:sinaAccount.userName userid:sinaAccount.usid];
                            [self thirdLogin:sinaAccount.usid nickname:sinaAccount.userName headerUrl:sinaAccount.iconURL type:1];
                        }
                    }];
                }
            });
            
        }
            break;
        default:
            break;
    }
}

#pragma mark -- UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField==self.textFieldAccount) {
        [self.textFieldPassword becomeFirstResponder];
    }else{
        [self.textFieldPassword resignFirstResponder];
    }
    return YES;
}

- (void)textFieldChanged:(id)sender
{
    NSString *account = self.textFieldAccount.text;
    if (account) {
        NSString *urlHeader = [QLPropertyUtils getStringByKey:[NSString stringWithFormat:@"userHeader_%@",account] defaultValue:nil];
        if (urlHeader) {
            self.imageViewUserHeader.layer.masksToBounds = YES;
            self.imageViewUserHeader.layer.cornerRadius = 40; //设置图片圆角的尺度
            [self.imageViewUserHeader setImageWithURL:[NSURL URLWithString:urlHeader] placeholderImage:[UIImage imageNamed:@"userlogin_usericon"]];
        }else{
            [self.imageViewUserHeader setImage:[UIImage imageNamed:@"userlogin_usericon"]];
        }
    }
}

@end
